package com.common.chris.core;

import com.common.chris.entity.R;
import com.common.chris.exception.BusinessException;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;

@RestControllerAdvice
public class GlobalController implements ResponseBodyAdvice {


    /**
     * 实现ResponseBodyAdvice 返回的参数可以进行报装 这个为true 就走beforeBodyWrite方法进行报装
     *
     * @param methodParameter
     * @param aClass
     * @return
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        // true 转换 false 不转换
        Class<?> returnType1 = methodParameter.getMethod().getReturnType();
        String returnTypeName = returnType1.getName();
        return !returnType1.isPrimitive() && // 判断是不是8中基本类型
                !returnTypeName.equals(String.class.getName()) &&
                !returnTypeName.equals(R.class.getName());
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        return new R(200, true, o);
    }

    @ExceptionHandler({NullPointerException.class})
    public R globalNullPointerException(HttpServletRequest req, Exception e){
        return new R(500, false, "空指针异常了");
    }


    @ExceptionHandler({BusinessException.class})
    public R globalBusinessException(HttpServletRequest req, BusinessException e){
        return new R(Integer.valueOf(e.getCode()), false, e.getMessage());
    }


    @ExceptionHandler({Exception.class})
    public R globalException(HttpServletRequest req, Exception e){
        return new R(500, false, e.getMessage());
    }

}
